package org.example.ssh

import net.schmizz.sshj.SSHClient
import net.schmizz.sshj.sftp.SFTPClient
import org.example.ssh.base.*

suspend fun main() {
    SSH.exec1(listOf("dev_redis-HK-1001")) {
        DeployRedis().deploySingle(it)
    }
}

class DeployRedis {
    var clusterDir = "/home/redis-cluster"
    var nodesNum = 3
    val password = "123qweQAZ@"

    suspend fun deploySingle(sshCtx: SshCtx) {
//        executeCmdPrint(sshCtx.cli, "docker stop myredis")
//        executeCmdPrint(sshCtx.cli, "docker ps")

//        val sftp = sshCtx.cli.newSFTPClient()
//        uploadDirectoryRecursive(sftp, "./配置/redis-single/${sshCtx.cName}", "/home")
//        executeCmdPrint(sshCtx.cli, "cd /home/${sshCtx.cName} && docker-compose -f redis-compose.yml up -d")

        // executeCmdPrint(sshCtx.cli, "cd /home${sshCtx.cName} && docker-compose -f redis-compose.yml down")
    }
    
    // 集群
    suspend fun deploy(ssh: SSHClient) {

//        syncConfig(ssh)
//        buildContainer(ssh)
//        downContainer(ssh)
//        clusterInit(ssh)


//        executeCmdPrint(ssh, "docker ps")
        // redis-cli -p 7000 MODULE LIST | grep Search

        val redisPreffix = "docker exec redis-node01 redis-cli -c -h 38.147.171.207 -p 7001 -a '$password'"
        executeCmdPrint(ssh, "$redisPreffix cluster nodes")
        executeCmdPrint(ssh, "$redisPreffix config get maxclients")
        executeCmdPrint(ssh, "$redisPreffix info clients")
    }

    suspend fun syncConfig(ssh: SSHClient) {
        val sftp: SFTPClient = ssh.newSFTPClient()
        for (i in 1..nodesNum) {
            val num = i.toString().padStart(2, '0')

            if (!exists(sftp, "${clusterDir}/node$num-data")) {
                mkdirs(sftp, "${clusterDir}/node$num-data")
            }
            sftp.put("./配置/redis/redis-$num.conf", "${clusterDir}/redis-$num.conf")
            sftp.put(
                "./配置/redis/redis-compose-$num.yml",
                "${clusterDir}/redis-compose-$num.yml"
            )
        }
        sftp.close()
    }

    suspend fun buildContainer(ssh: SSHClient) {
        for (i in 1..nodesNum) {
            val num = i.toString().padStart(2, '0')
            executeCmdPrint(ssh, "cd $clusterDir && docker-compose -f redis-compose-$num.yml up -d")
        }
    }

    suspend fun downContainer(ssh: SSHClient) {
        for (i in 3..nodesNum) {
            val num = i.toString().padStart(2, '0')
            executeCmdPrint(ssh, "cd $clusterDir && docker-compose -f redis-compose-$num.yml down")
        }
    }

    suspend fun clusterInit(ssh: SSHClient) {
        executeCmdPrint(
            ssh,
            "docker run -it --rm redis:6.2.10 redis-cli --cluster create 38.147.171.207:7001 38.147.171.207:7002 38.147.171.207:7003 --cluster-replicas 0 -a '$password' --cluster-yes "
        )
    }
}